import Taro from "@tarojs/taro";
import { ServerHost, getRuntime } from "./common";
const { getToken, navigateTo, showToast } = getRuntime();

/*function parseJSON(response) {
  return response.json();
}*/

function checkStatus(response, callback) {
  if (response.statusCode == 401) {
    const error = new Error("clear");
    error["response"] = response;
    error["callback"] = callback;
    throw error;
  }
  return response;
}

function checkSuccess(data, callback) {
  if (data.success === true) {
    Taro.hideLoading()
    return data.result;
  } else {
    const error = new Error(data.error.message);
    error["response"] = data.error.details;
    error["callback"] = callback;
    throw error;
  }
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request({ url, options },   callback?, isLoading = true) {
  options.headers = Object.assign({}, options.headers, getToken());
  const { body, headers, method } = options;
  if (isLoading) {
    Taro.showLoading({
      title: '加载中...',
      mask: true
    });
  }
  return Taro.request({
    url: ServerHost + url,
    data: body,
    header: headers,
    method: method
  })
    .then(res => checkStatus(res, callback))
    .then(res => res.data)
    .then(data => checkSuccess(data, callback))
    .catch(err => {
      if (err.message == "clear") {
        setTimeout(() => {
          // navigateTo("../user/Wxlogin");
          navigateTo("/pages/other/bindPhone")
        }, 1000);
        throw err;
      }
      else {
        showToast(err.message, 'none');
        throw err;
      }
    });
}
